import {
  addCourseUsingPost,
  updateCourseUsingPut,
} from '@/services/student-management-system/kechengmokuai';
import {Form, Input, message} from 'antd';
import {forwardRef, useEffect, useImperativeHandle} from 'react';

export interface UpdateCourseProps {
  editCourse?: API.CourseDTO;
  onCloseModal?: () => void;
}

export interface UpdateCourseMethods {
  submitForm: () => Promise<boolean>;
}

const UpdateCourse = forwardRef<UpdateCourseMethods, UpdateCourseProps>((props, ref) => {
  const {editCourse, onCloseModal} = props;
  const [form] = Form.useForm();

  const submitForm = async (): Promise<boolean> => {
    // 获取表单提交数据
    const values = await form.validateFields();
    const res = editCourse?.id
      ? await updateCourseUsingPut({...values, id: editCourse.id})
      : await addCourseUsingPost({...values});
    if (res.code === 200) {
      message.success('操作成功');
      onCloseModal?.();
      return true;
    } else {
      message.error('操作失败：' + res.msg);
      return false;
    }
  };
  useEffect(() => {
    if (editCourse) {
      form.setFieldsValue({
        courseName: editCourse.courseName,
        credit: editCourse.credit,
        hours: editCourse.hours,
        description: editCourse.description,
      });
    }
  }, [editCourse]);

  useImperativeHandle(ref, () => ({
    submitForm,
  }));

  return (
    <Form form={form} labelCol={{span: 6}} wrapperCol={{span: 16}} autoComplete="off">
      <Form.Item label="课程名称" name="courseName" rules={[{required: true}]}>
        <Input/>
      </Form.Item>

      <Form.Item label="学分" name="credit" rules={[{required: true}]}>
        <Input type="number" step="0.5"/>
      </Form.Item>

      <Form.Item label="学时" name="hours" rules={[{required: true}]}>
        <Input type="number"/>
      </Form.Item>

      <Form.Item label="描述" name="description">
        <Input.TextArea rows={3}/>
      </Form.Item>
    </Form>
  );
});

export default UpdateCourse;
